<template>
  <div class="login">
    <nav-bar :title="navTitle"></nav-bar>
    <van-form @submit="onSubmit">
      <van-field
        v-model="form.phone"
        name="手机号"
        label="手机号"
        placeholder="请输入手机号"
        :rules="[
          { required: true, message: '请输入手机号' },
          { pattern, message: '请输入11位的手机号'}
        ]"
      />
      <van-field
        v-model="form.password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[
          { required: true, message: '请填写密码' },
          { validator, message: '密码要求在6-18位'}
        ]"
      />
      <div style="margin: 16px;">
        <van-button
          round
          block
          :loading="isLoading"
          type="info"
          loading-text="加载中..."
          native-type="submit"
        >登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { Form, Field, Button } from 'vant'
import navBar from '@/components/navBar'
import { login } from '@/services/login'
import store from '@/store'
export default {
  name: 'login',
  components: {
    navBar,
    VanForm: Form,
    VanField: Field,
    VanButton: Button
  },
  data () {
    return {
      navTitle: '登录',
      form: {
        phone: 18201288771,
        password: 111111
      },
      pattern: /^1\d{10}$/,
      isLoading: false
    }
  },
  methods: {
    // 密码校验
    validator (val) {
      return /^[a-zA-Z0-9]{6,12}$/.test(val)
    },
    // 提交
    async onSubmit () {
      this.isLoading = true
      const { data } = await login(this.form)
      console.log(data)
      if (data.state === 1) {
        // 登录后,存储返回的access_token值,以便后面需要token的页面使用
        store.commit('setUser', data.content)
        // 跳转到目标页(根据导航守卫设置的位置)
        this.$router.push(this.$route.query.redirect || '/')
      }
      this.isLoading = false
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
